package com.nuo.image.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.nuo.image.po.AddOrPutPO;
import com.nuo.image.po.UrlPO;
import com.nuo.image.util.Base64Util;
import com.nuo.image.util.FileUtil;
import com.nuo.image.util.HttpUtil;
import com.nuo.image.config.ImageConfig;
import com.nuo.image.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * @description: TODO
 * @author nuo
 * @date 2023/2/16 18:13
 * @version 1.0
 */
@Service
public class ImageServiceImpl implements ImageService {

    @Autowired
    private ImageConfig imageConfig;

    @Override
    public String getToken() {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + imageConfig.getApiKey()
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + imageConfig.getSecretKey();
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            return jsonObject.getString("access_token");
        } catch (Exception e) {
            System.err.println("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }

    @Override
    public String getCheckToken() {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + imageConfig.getCheckApiKey()
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + imageConfig.getCheckSecretKey();
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            return jsonObject.getString("access_token");
        } catch (Exception e) {
            System.err.println("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }

    @Override
    public Object getInfoByUrl(UrlPO po) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general";
        try {
            String data = "url=" + po.getImageUrl();
            return HttpUtil.post(url, getToken(), data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Object getInfoByFile(MultipartFile image) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general";
        try {
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getToken();

            byte[] imgData = image.getBytes();
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String data = "image=" + imgParam;

            String result = HttpUtil.post(url, accessToken, data);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Object add(AddOrPutPO po) {
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/add";
        try {
            String param = "url=" + po.getImageUrl() + "&brief=" + JSONObject.toJSONString(po.getBrief()) + "&tags=" + "1,1";
            return HttpUtil.post(url, getCheckToken(), param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Object del(UrlPO po) {
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/delete";
        try {
            String data = "url=" + po.getImageUrl();
            return HttpUtil.post(url, getCheckToken(), data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Object put(AddOrPutPO po) {
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/update";
        try {
            String param = "brief=" + JSONObject.toJSONString(po.getBrief()) + "&url=" + po.getImageUrl() + "&tags=" + "1,1";
            return HttpUtil.post(url, getCheckToken(), param);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    @Override
    public Object getCheckInfoByUrl(UrlPO po) {
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/search";
        try {
            String data = "url=" + po.getImageUrl();
            return HttpUtil.post(url, getCheckToken(), data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Object getCheckInfoByFile(MultipartFile image) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/search";
        try {
            byte[] imgData = image.getBytes();
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String data = "image=" + imgParam;

            String result = HttpUtil.post(url, getCheckToken(), data);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
